package com.heima.intercept;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName FeignAuthRequestInterceptor.java
 * @Description feign请求授权拦截器
 */
@Slf4j
public class FeignAuthRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        log.info(" ================= feign拦截器触发 ===================");
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null){
            log.info("没有web请求上下文信息");
            return;
        }

        ServletRequestAttributes attributes =
                (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String userId = request.getHeader("userId");
        if (StringUtils.isNotBlank(userId)){
            template.header("userId", userId);
        }
        String userType = request.getHeader("userType");
        if (StringUtils.isNotBlank(userType)){
            template.header("userType", userType);
        }
        log.info(" ================= userId: {}   userType:{}  ===================",userId,userType);
        log.info(" ================= feign拦截器触发 ===================");
    }
}
